<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>乐康养老管理系统</h1>
    </div>

    <!-- 第一行：数据概览 + 我的信息 -->
    <div class="grid-row">
      <!-- 数据概览 -->
      <el-card shadow="hover" class="card-item overview-card">
        <div class="card-header" style="margin-top: 20px;">
          <h2>数据概览</h2>
          <span class="update-time">数据更新：{{ statsUpdateTime }}</span>
        </div>
        <div class="overview-items">
          <!-- 老人数量 -->
          <div class="overview-item" style="margin-left: 18px;margin-top: 20px;">
            <el-tooltip :content="`还可容纳老人数量:${remainingElderly}人`" placement="top">
              <el-progress 
                type="circle" 
                :percentage="calculatePercentage(dashboardStats.elderlyCount, dashboardStats.totalBeds)" 
                :format="(p) => `老人数量${formatNumber(dashboardStats.elderlyCount)}人`" 
                stroke-width="18"
                color="#C9E2FC"
              />
            </el-tooltip>
          </div>
          <!-- 床位数 -->
          <div class="overview-item" style="margin-left: 18px;margin-top: 20px;">
            <el-tooltip :content="`剩余床位:${remainingBeds}个`" placement="top">
            <el-progress 
              type="circle" 
              :percentage="100" 
              :format="(p) => `床位数${formatNumber(dashboardStats.totalBeds)}个`" 
              color="#B8E6C9"
              stroke-width="18"
            />
            </el-tooltip>
          </div>
          <!-- 服务单数量 -->
          <div class="overview-item" style="margin-left: 18px;margin-top: 20px;">
            <el-tooltip :content="`服务单数量:${formatNumber(dashboardStats.orderCount)}笔`" placement="top">
            <el-progress 
              type="circle" 
              :percentage="calculateOrderPercentage()" 
              :format="(p) => `服务单${formatOrderCount(dashboardStats.orderCount)}`" 
              color="#CBCFF0"
              stroke-width="18"
            />
            </el-tooltip>
          </div>
          <!-- 员工数量 -->
          <div class="overview-item" style="margin-left: 18px;margin-top: 20px;">
            <el-tooltip :content="`员工数量:${formatNumber(dashboardStats.userCount)}人`" placement="top">
            <el-progress 
              type="circle" 
              :percentage="calculateUserPercentage()" 
              :format="(p) => `员工数量${formatNumber(dashboardStats.userCount)}人`" 
              color="#FFF2D8"
              stroke-width="18"
            />
            </el-tooltip>
          </div>
          <!-- 收入金额 -->
          <div class="overview-item" style="margin-left: 18px;margin-top: 20px;">
            <el-tooltip :content="`收入金额:${formatAmount(dashboardStats.totalIncome)}`" placement="top">
            <el-progress 
              type="circle" 
              :percentage="calculateIncomePercentage()" 
              :format="(p) => `收入${formatIncome(dashboardStats.totalIncome)}`" 
              color="#FFD7D7"
              stroke-width="18"
            />
            </el-tooltip>
          </div>
        </div>
      </el-card>

      <!-- 我的信息（已删除下属员工，新增系统公告） -->
      <el-card shadow="hover" class="card-item info-card">
        <div class="card-header">
          <h2>我的信息</h2>
          <el-button 
            text 
            class="badge-button" 
            @click="handleClick"
          >
            <span>新消息</span>
            <el-badge 
              v-if="unreadCount > 0" 
              :value="unreadCount" 
              type="primary"
              class="badge"
            />
          </el-button>
        </div>
        <div class="user-info">
          <el-avatar :size="100" class="main-avatar">
            <img :src="userInfo.avatar || 'https://picsum.photos/id/1012/200/200'" alt="个人头像" />
          </el-avatar>
          <div class="info-text">
            <p class="greeting">您好，<span class="username-highlight">{{ userInfo.nickName || userInfo.userName || '顾廷烨' }}</span>，今天也是元气满满的一天！</p>
            <div class="info-details">
              <div class="detail-row">
                <el-icon class="detail-icon"><User /></el-icon>
                <span class="detail-label">账号：</span>
                <span class="detail-value">{{ userInfo.userName || 'guthingye0405' }}</span>
              </div>
              <div class="detail-row">
                <el-icon class="detail-icon"><OfficeBuilding /></el-icon>
                <span class="detail-label">部门：</span>
                <span class="detail-value">{{ userInfo.dept?.deptName || '养老院管理部' }}</span>
              </div>
              <div class="detail-row">
                <el-icon class="detail-icon"><UserFilled /></el-icon>
                <span class="detail-label">状态：</span>
                <span class="detail-value">{{ userInfo.status === '0' ? '启用' : '禁用' }}</span>
              </div>
              <div class="detail-row">
                <el-icon class="detail-icon"><Clock /></el-icon>
                <span class="detail-label">最后登录：</span>
                <span class="detail-value">{{ formatTime(userInfo.loginDate) || '2024-10-01 09:00:00' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 新增：系统公告（非隐私数据） -->
        <div class="notice-section">
          <h3>系统公告</h3>
          <div class="notice-list">
            <template v-for="(notice, index) in noticeList" :key="index">
              <el-card shadow="never" class="notice-card">
                <h4 class="notice-title">{{ notice.noticeTitle }}</h4>
                <p class="notice-content">{{ notice.noticeContent }}</p>
                <p class="notice-time">发布时间：{{ formatTime(notice.createTime) }}</p>
              </el-card>
            </template>
            <el-card v-if="noticeList.length === 0" shadow="never" class="empty-notice">
              暂无系统公告
            </el-card>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 第二行：数据统计 + 快捷方式 -->
    <div class="grid-row">
      <!-- 数据统计 -->
      <el-card shadow="hover" class="card-item stats-card">
        <div class="card-header">
          <h2>数据统计</h2>
        </div>
        <el-tabs v-model="activeTab" class="stats-tabs">
          <el-tab-pane label="收益情况" name="income"></el-tab-pane>
          <el-tab-pane label="入退情况" name="in-out"></el-tab-pane>
          <el-tab-pane label="服务情况" name="service"></el-tab-pane>
        </el-tabs>
        <div ref="chartRef" class="chart-container"></div>
        <div class="date-filter">
          <el-radio-group v-model="dateRange" @change="handleDateChange">
            <el-radio label="今日">今日</el-radio>
            <el-radio label="本周">本周</el-radio>
            <el-radio label="本月">本月</el-radio>
          </el-radio-group>
          <el-date-picker
            v-model="customDate"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="custom-date-picker"
          />
        </div>
      </el-card>

      <!-- 快捷方式 -->
      <el-card shadow="hover" class="card-item shortcuts-card">
        <div class="card-header">
          <h2>快捷方式</h2>
        </div>
        <div class="shortcuts-container">
          <div class="shortcut-item" @click="handleShortcut1">
            <el-badge :value="15" class="badge">
              <el-icon class="shortcut-icon"><DocumentChecked /></el-icon>
            </el-badge>
            <p>待办事项</p>
          </div>
          <div class="shortcut-item" @click="handleShortcut2">
            <el-icon class="shortcut-icon"><Money /></el-icon>
            <p>入账列表</p>
          </div>
          <div class="shortcut-item" @click="handleShortcut3">
            <el-icon class="shortcut-icon"><UserFilled /></el-icon>
            <p>护理记录</p>
          </div>
          <div class="shortcut-item" @click="handleShortcut4">
            <el-icon class="shortcut-icon"><View /></el-icon>
            <p>健康检查</p>
          </div>
          <div class="shortcut-item" @click="handleShortcut5">
            <el-icon class="shortcut-icon"><Tickets /></el-icon>
            <p>活动安排</p>
          </div>
          <div class="shortcut-item" @click="handleShortcut6">
            <el-icon class="shortcut-icon"><Monitor /></el-icon>
            <p>设备维护</p>
          </div>
          <div class="shortcut-item" @click="handleShortcut7">
            <el-icon class="shortcut-icon"><User /></el-icon>
            <p>员工管理</p>
          </div>
          <div class="shortcut-item" @click="handleShortcut8">
            <el-icon class="shortcut-icon"><Setting /></el-icon>
            <p>系统设置</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 第三行：待办事项 + 预约总览 -->
    <div class="grid-row">
      <!-- 待办事项 -->
      <el-card shadow="hover" class="card-item todo-card">
        <div class="card-header">
          <h2>待办事项</h2>
          <el-button type="text" class="more-btn">查看全部</el-button>
        </div>
        <div class="todo-list">
          <div class="todo-item">
            <el-tag type="info" class="todo-tag">入住</el-tag>
            <div class="todo-content">
              <p class="todo-title">SP2048101015000001 高启强的入住申请</p>
              <p class="todo-meta">申请人：顾廷烨 申请时间：2023-10-10 15:00:00</p>
            </div>
            <el-button type="primary" size="small">审批</el-button>
          </div>
          <div class="todo-item">
            <el-tag type="info" class="todo-tag">入住</el-tag>
            <div class="todo-content">
              <p class="todo-title">SP2048101015000001 高启强的入住申请</p>
              <p class="todo-meta">申请人：顾廷烨 申请时间：2023-10-10 15:00:00</p>
            </div>
            <el-button type="primary" size="small">审批</el-button>
          </div>
          <div class="todo-item">
            <el-tag type="warning" class="todo-tag">请假</el-tag>
            <div class="todo-content">
              <p class="todo-title">SP2048101109300002 孟德海的请假申请</p>
              <p class="todo-meta">申请人：李响 申请时间：2023-10-11 09:30:00</p>
            </div>
            <el-button type="primary" size="small">审批</el-button>
          </div>
          <div class="todo-item">
            <el-tag type="danger" class="todo-tag">退住</el-tag>
            <div class="todo-content">
              <p class="todo-title">SP2048101214150003 赵立冬的退住申请</p>
              <p class="todo-meta">申请人：安欣 申请时间：2023-10-12 14:15:00</p>
            </div>
            <el-button type="primary" size="small">审批</el-button>
          </div>
          <div class="todo-item">
            <el-tag type="success" class="todo-tag">采购</el-tag>
            <div class="todo-content">
              <p class="todo-title">CG2048101310000004 医疗用品采购申请</p>
              <p class="todo-meta">申请人：张彪 申请时间：2023-10-13 10:00:00</p>
            </div>
            <el-button type="primary" size="small">审批</el-button>
          </div>
          <div class="todo-item">
            <el-tag type="danger" class="todo-tag">退住</el-tag>
            <div class="todo-content">
              <p class="todo-title">SP2048101214150003 赵立冬的退住申请</p>
              <p class="todo-meta">申请人：安欣 申请时间：2023-10-12 14:15:00</p>
            </div>
            <el-button type="primary" size="small">审批</el-button>
          </div>
        </div>
      </el-card>

      <!-- 预约总览 -->
      <el-card shadow="hover" class="card-item reservation-card">
        <div class="card-header">
          <h2>预约总览</h2>
          <el-button type="text" class="more-btn" @click="handleViewAll">查看全部</el-button>
        </div>
        <div class="date-nav">
          <el-button size="small" @click="prevDate">
            <ArrowLeft />
          </el-button>
          <span class="current-date">{{ currentDate }}</span>
          <el-button size="small" @click="nextDate">
            <ArrowRight />
          </el-button>
          <el-button type="text" size="small" @click="today">回到今日</el-button>
        </div>
        <div class="reservation-list">
          <div 
            v-for="item in reservationList" 
            :key="item.id" 
            class="reservation-item"
          >
            <el-tag type="info" class="time-tag">
              {{ formatAppointmentTime(item.appointmentTime) }}
            </el-tag>
            <el-tag 
              :type="getAppointmentTypeTagType(item.appointmentType)" 
              class="type-tag"
            >
              {{ getAppointmentTypeLabel(item.appointmentType) }}
            </el-tag>
            <div class="reservation-content">
              <p>预约人姓名：{{ item.applicantName }}</p>
              <p>预约人手机号：{{ item.phone }}</p>
              <p v-if="item.elderly && item.elderly.name">老人姓名：{{ item.elderly.name }}</p>
              <p class="reservation-status">
                <el-tag 
                  :type="getStatusTagType(item.status)" 
                  size="small"
                >
                  {{ getStatusLabel(item.status) }}
                </el-tag>
              </p>
            </div>
          </div>
          <div v-if="reservationList.length === 0" class="no-data">
            <el-empty description="暂无预约数据" :image-size="80" />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 第四行：老人分布与服务能力 -->
    <div class="grid-row">
      <!-- 老人等级分布 -->
      <el-card shadow="hover" class="card-item distribution-card">
        <div class="card-header">
          <h2>老人等级分布</h2>
          <span class="update-time">数据更新：{{ levelUpdateTime }}</span>
        </div>
        <div ref="levelChartRef" class="small-chart"></div>
      </el-card>

      <el-card shadow="hover" class="card-item distribution-card">
        <div class="card-header">
          <h2>老人年龄分布</h2>
          <span class="update-time">数据更新：{{ ageUpdateTime }}</span>
        </div>
        <div v-if="ageChartDataEmpty" class="empty-chart">
          <el-empty description="暂无老人数据" :image-size="80" />
        </div>
        <div v-else ref="ageChartRef" class="small-chart"></div>
      </el-card>

      <!-- 养老服务能力 -->
      <el-card shadow="hover" class="card-item distribution-card">
        <div class="card-header">
          <h2>养老服务能力</h2>
          <span class="update-time">数据更新：{{ serviceUpdateTime }}</span>
        </div>
        <div ref="serviceChartRef" class="small-chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, getCurrentInstance, computed } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import { 
  Refresh, ArrowLeft, ArrowRight, DocumentChecked, 
  Money, UserFilled, View, Tickets, Monitor, 
  User, Setting, OfficeBuilding, Location, Clock
} from '@element-plus/icons-vue'
import { ElMessage, ElEmpty } from 'element-plus'

// 导入API接口
import { 
  listElderly, 
  listRoom, 
  listOrderManagement, 
  listSysUser 
} from '@/api/system/gzt' // 根据实际路径调整
import { listRegistration } from '@/api/system/registration'
import { getUserProfile } from '@/api/system/user'
import { listNotice } from '@/api/system/notice'

const router = useRouter()
const { proxy } = getCurrentInstance()

// 状态管理
const activeTab = ref('service')
const dateRange = ref('本周')
const customDate = ref(['2023-10-09', '2023-10-15'])
const currentDate = ref(formatDate(new Date()))
const chartRef = ref(null)
const levelChartRef = ref(null)
const ageChartRef = ref(null)
const serviceChartRef = ref(null)

// 核心数据
const userInfo = ref({})
const noticeList = ref([])
const reservationList = ref([])
const loading = ref(false)
const unreadCount = ref(3) // 示例未读消息数量

// 工作台统计数据
const dashboardStats = ref({
  elderlyCount: 0,      // 老人数量
  totalBeds: 0,         // 床位数
  orderCount: 0,        // 服务单数量
  userCount: 0,         // 员工数量
  totalIncome: 0        // 收入金额
})

// 数据更新时间
const levelUpdateTime = ref('--')
const ageUpdateTime = ref('--')
const serviceUpdateTime = ref('--')
const statsUpdateTime = ref('--')

// 计算属性
const remainingElderly = computed(() => {
  return Math.max(0, dashboardStats.value.totalBeds - dashboardStats.value.elderlyCount)
})

const remainingBeds = computed(() => {
  return Math.max(0, dashboardStats.value.totalBeds - dashboardStats.value.elderlyCount)
})

let mainChart = null
let levelChart = null
let ageChart = null
let serviceChart = null

// 初始化图表和数据
onMounted(() => {
  initMainChart()
  initLevelChart()
  initAgeChartWithRealData()
  initServiceChart()
  loadReservationData()
  loadUserProfile()
  loadNoticeList()
  loadDashboardStats() // 加载工作台统计数据
})

// 加载工作台统计数据
const loadDashboardStats = async () => {
  try {
    console.log('开始加载工作台统计数据...')
    
    // 并行请求所有统计数据
    const [elderlyRes, roomRes, orderRes, userRes] = await Promise.all([
      listElderly({ pageSize: 1, pageNum: 1 }), // 只获取总数
      listRoom({ pageSize: 1000 }), // 获取所有房间计算床位总数
      listOrderManagement({ pageSize: 1, pageNum: 1 }), // 只获取总数
      listSysUser({ pageSize: 1, pageNum: 1 }) // 只获取总数
    ])
    
    console.log('统计数据响应:', { elderlyRes, roomRes, orderRes, userRes })
    
    // 处理老人数量
    if (elderlyRes.code === 200) {
      dashboardStats.value.elderlyCount = elderlyRes.total || 0
    }
    
    // 处理床位数 - 计算所有房间的totalBeds总和
    if (roomRes.code === 200 && roomRes.rows) {
      dashboardStats.value.totalBeds = roomRes.rows.reduce((sum, room) => {
        return sum + (Number(room.totalBeds) || 0)
      }, 0)
    }
    
    // 处理订单数量
    if (orderRes.code === 200) {
      dashboardStats.value.orderCount = orderRes.total || 0
      
      // 计算订单总金额 - 如果需要计算收入，需要获取所有订单数据
      // 这里假设需要计算收入，获取所有订单
      const allOrdersRes = await listOrderManagement({ pageSize: 1000 })
      if (allOrdersRes.code === 200 && allOrdersRes.rows) {
        dashboardStats.value.totalIncome = allOrdersRes.rows.reduce((sum, order) => {
          return sum + (Number(order.orderAmount) || 0)
        }, 0)
      }
    }
    
    // 处理员工数量
    if (userRes.code === 200) {
      dashboardStats.value.userCount = userRes.total || 0
    }
    
    // 更新统计时间
    statsUpdateTime.value = formatDate(new Date())
    
    console.log('最终统计数据:', dashboardStats.value)
    
  } catch (error) {
    console.error('加载工作台统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

// 1. 个人信息加载
const loadUserProfile = async () => {
  try {
    const res = await getUserProfile()
    if (res.code === 200) {
      userInfo.value = res.data || {}
    }
  } catch (error) {
    console.error('加载个人信息失败:', error)
  }
}

// 2. 系统公告加载
const loadNoticeList = async () => {
  try {
    const res = await listNotice({ 
      pageNum: 1, 
      pageSize: 3,
      noticeType: '1'
    })
    if (res.code === 200) {
      noticeList.value = res.rows || []
    }
  } catch (error) {
    console.error('加载系统公告失败:', error)
  }
}

// 3. 预约数据加载
async function loadReservationData() {
  try {
    loading.value = true
    const queryParams = {
      pageNum: 1,
      pageSize: 4,
      appointmentTime: currentDate.value
    }
    const response = await listRegistration(queryParams)
    if (response.code === 200) {
      reservationList.value = response.rows || []
    } else {
      ElMessage.error('获取预约数据失败')
      reservationList.value = []
    }
  } catch (error) {
    console.error('加载预约数据失败:', error)
    ElMessage.error('加载预约数据失败')
    reservationList.value = []
  } finally {
    loading.value = false
  }
}

// 工具方法 - 格式化数字（添加千分位分隔符）
function formatNumber(num) {
  return Number(num).toLocaleString('zh-CN')
}

// 工具方法 - 格式化金额（万元显示）
function formatAmount(amount) {
  const wan = Number(amount) / 10000
  return wan >= 1 ? `${wan.toFixed(1)}W` : `${amount}`
}

// 工具方法 - 格式化收入显示
function formatIncome(amount) {
  const wan = Number(amount) / 10000
  if (wan >= 100) {
    return `${(wan / 100).toFixed(1)}亿`
  } else if (wan >= 1) {
    return `${wan.toFixed(1)}W元`
  } else {
    return `${amount}元`
  }
}

// 工具方法 - 格式化订单数量显示
function formatOrderCount(count) {
  const wan = Number(count) / 10000
  if (wan >= 1) {
    return `${wan.toFixed(1)}w笔`
  } else {
    return `${count}笔`
  }
}

// 工具方法 - 计算百分比（用于进度圈）
function calculatePercentage(current, total) {
  if (!total || total === 0) return 0
  return Math.round((current / total) * 100)
}

// 计算订单进度百分比
function calculateOrderPercentage() {
  const baseCount = 10000 // 基准值
  return Math.min(100, Math.round((dashboardStats.value.orderCount / baseCount) * 100))
}

// 计算员工进度百分比
function calculateUserPercentage() {
  const baseCount = 200 // 基准值
  return Math.min(100, Math.round((dashboardStats.value.userCount / baseCount) * 100))
}

// 计算收入进度百分比
function calculateIncomePercentage() {
  const baseAmount = 1000000 // 基准值100万
  return Math.min(100, Math.round((dashboardStats.value.totalIncome / baseAmount) * 100))
}

// 其他现有方法保持不变...
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function formatTime(dateTime) {
  if (!dateTime) return '--'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

function formatAppointmentTime(dateTime) {
  if (!dateTime) return '--:--'
  const date = new Date(dateTime)
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 5. 预约相关状态映射
function getAppointmentTypeTagType(type) {
  const typeMap = { '0': 'warning', '1': 'primary' }
  return typeMap[type] || 'info'
}
function getAppointmentTypeLabel(type) {
  const typeMap = { '0': '参观', '1': '探访' }
  return typeMap[type] || '其他'
}
function getStatusTagType(status) {
  const statusMap = { '0': 'info', '1': 'success', '2': 'warning', '3': 'danger' }
  return statusMap[status] || 'info'
}
function getStatusLabel(status) {
  const statusMap = { '0': '已取消', '1': '已完成', '2': '待上门', '3': '已过期' }
  return statusMap[status] || status
}

// 6. 图表初始化
function initMainChart() {
  if (chartRef.value) {
    mainChart = echarts.init(chartRef.value)
    updateMainChartData()
  }
}
function updateMainChartData() {
  if (!mainChart) return
  const xAxisData = dateRange.value === '今日' 
    ? ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00']
    : ['10-09', '10-10', '10-11', '10-12', '10-13', '10-14', '10-15']
  const seriesData = dateRange.value === '今日'
    ? [5, 3, 2, 8, 15, 12, 7, 4,10,12,15,18]
    : [66, 12, 36, 81, 23, 12, 71]
  
  mainChart.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: { color: '#333' },
      formatter: params => `${params[0].name}: ${params[0].value} 次服务`
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: xAxisData, axisLine: { lineStyle: { color: '#eee' } } },
    yAxis: { type: 'value', axisLine: { lineStyle: { color: '#eee' } }, splitLine: { lineStyle: { color: '#f5f5f5' } } },
    series: [{
      data: seriesData,
      type: 'line',
      smooth: true,
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{ offset: 0, color: 'rgba(64, 158, 255, 0.3)' }, { offset: 1, color: 'rgba(64, 158, 255, 0)' }]
        }
      },
      lineStyle: { width: 3, color: '#409EFF' },
      itemStyle: { color: '#409EFF', borderWidth: 2, borderColor: '#fff', shadowBlur: 4, shadowColor: 'rgba(0, 0, 0, 0.1)' }
    }]
  })
}

function initLevelChart() {
  if (levelChartRef.value) {
    levelChart = echarts.init(levelChartRef.value)
    levelChart.setOption({
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', left: 10, textStyle: { fontSize: 12 }, top: 'center' },
      series: [{
        name: '护理等级',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 4, borderColor: '#fff', borderWidth: 2 },
        label: { show: false, position: 'center' },
        emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: [
          { value: 4, name: '特级护理' },
          { value: 20, name: '一级护理' },
          { value: 56, name: '二级护理' },
          { value: 120, name: '三级护理' },
          { value: 285, name: '四级护理' }
        ]
      }]
    })
    levelUpdateTime.value = formatDate(new Date())
  }
}

// 在script setup中添加这个响应式变量
const ageChartDataEmpty = ref(false)

async function initAgeChartWithRealData() {
  if (!ageChartRef.value) return
  ageChart = echarts.init(ageChartRef.value)
  ageChart.showLoading({
    text: '正在加载老人数据...',
    color: '#409EFF',
    textColor: '#333',
    maskColor: 'rgba(255, 255, 255, 0.8)'
  })
  
  try {
    console.log('开始请求老人数据...')
    const response = await listElderly({ pageSize: 1000, pageNum: 1 })
    console.log('API响应:', response)
    
    if (response.code === 200 && response.rows) {
      console.log('获取到的老人数据:', response.rows)
      
      const ageDistribution = calculateAgeDistribution(response.rows)
      console.log('计算后的年龄分布:', ageDistribution)
      
      // 检查是否有数据
      const hasData = Object.values(ageDistribution).some(item => item.male > 0 || item.female > 0)
      ageChartDataEmpty.value = !hasData
      
      if (hasData) {
        ageUpdateTime.value = formatDate(new Date())
        
        ageChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: params => {
              const male = params[0], female = params[1]
              return `${male.name}<br/>${male.marker} 男: ${male.value}人<br/>${female.marker} 女: ${female.value}人<br/>总计: ${male.value + female.value}人`
            }
          },
          legend: { data: ['男', '女'], top: 0, textStyle: { fontSize: 12 } },
          grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
          xAxis: {
            type: 'category',
            data: Object.keys(ageDistribution),
            axisLabel: { fontSize: 12, interval: 0, rotate: 0 }
          },
          yAxis: { type: 'value', axisLabel: { fontSize: 12 }, name: '人数' },
          series: [
            {
              name: '男',
              type: 'bar',
              data: Object.values(ageDistribution).map(item => item.male),
              itemStyle: { color: '#409EFF', borderRadius: [2, 2, 0, 0] },
              label: { show: true, position: 'top', fontSize: 11 }
            },
            {
              name: '女',
              type: 'bar',
              data: Object.values(ageDistribution).map(item => item.female),
              itemStyle: { color: '#E6A23C', borderRadius: [2, 2, 0, 0] },
              label: { show: true, position: 'top', fontSize: 11 }
            }
          ]
        })
      } else {
        ageChart.setOption({
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: { text: '暂无老人数据\n请先添加老人信息', fontSize: 14, fill: '#999', textAlign: 'center' }
          }
        })
      }
    } else {
      console.warn('API返回数据异常:', response)
      ageChartDataEmpty.value = true
      ageChart.setOption({
        graphic: {
          type: 'text',
          left: 'center',
          top: 'middle',
          style: { text: '数据加载失败\n请检查网络连接', fontSize: 14, fill: '#999', textAlign: 'center' }
        }
      })
    }
  } catch (error) {
    console.error('初始化年龄分布图表失败:', error)
    ageChartDataEmpty.value = true
    ageChart.setOption({
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: { text: '数据加载异常\n请稍后重试', fontSize: 14, fill: '#999', textAlign: 'center' }
      }
    })
  } finally {
    ageChart.hideLoading()
  }
}

// 确保calculateAgeDistribution函数正确
function calculateAgeDistribution(elderlyList) {
  console.log('计算年龄分布，输入数据:', elderlyList)
  
  const ageGroups = {
    '60岁以下': { male: 0, female: 0 },
    '60-70岁': { male: 0, female: 0 },
    '71-80岁': { male: 0, female: 0 },
    '81-90岁': { male: 0, female: 0 },
    '90岁以上': { male: 0, female: 0 }
  }

  elderlyList.forEach((elderly, index) => {
    console.log(`处理第${index + 1}个老人:`, elderly)
    
    // 调试：查看老人对象的所有字段
    console.log('老人对象字段:', Object.keys(elderly))
    
    // 尝试多种可能的年龄字段名
    const age = elderly.age || elderly.elderlyAge || elderly.currentAge || 0
    // 尝试多种可能的性别字段名
    const gender = elderly.sex || elderly.gender || elderly.elderlyGender || ''
    
    console.log(`解析结果 - 年龄: ${age}, 性别: ${gender}`)
    
    // 确定年龄分组
    let group
    if (age < 60) group = '60岁以下'
    else if (age <= 70) group = '60-70岁'
    else if (age <= 80) group = '71-80岁'
    else if (age <= 90) group = '81-90岁'
    else group = '90岁以上'
    
    // 统计性别
    if (gender === '1' || gender === '男' || gender === 'male' || gender === 'M') {
      ageGroups[group].male++
      console.log(`分配到 ${group} - 男性`)
    } else if (gender === '0' || gender === '女' || gender === 'female' || gender === 'F') {
      ageGroups[group].female++
      console.log(`分配到 ${group} - 女性`)
    } else {
      console.warn(`未知性别: "${gender}"，老人ID: ${elderly.id || '未知'}`)
      // 可以选择默认分配到某一组或忽略
    }
  })
  
  console.log('最终年龄分布:', ageGroups)
  return ageGroups
}

function initServiceChart() {
  if (serviceChartRef.value) {
    serviceChart = echarts.init(serviceChartRef.value)
    serviceChart.setOption({
      tooltip: { trigger: 'item' },
      radar: {
        indicator: [
          { name: '助餐', max: 10 },
          { name: '口部清洁', max: 10 },
          { name: '洗头', max: 10 },
          { name: '复健运动', max: 10 },
          { name: '助浴', max: 10 }
        ],
        splitArea: { areaStyle: { color: ['rgba(255,255,255,0.1)', 'rgba(255,255,255,0.2)'] } }
      },
      series: [{
        name: '服务能力',
        type: 'radar',
        symbolSize: 6,
        lineStyle: { width: 2 },
        areaStyle: { color: 'rgba(64, 158, 255, 0.2)' },
        data: [{ value: [8, 9, 7, 6, 8], name: '服务单数量' }]
      }]
    })
    serviceUpdateTime.value = formatDate(new Date())
  }
}

// 7. 其他交互方法
async function refreshData() {
  ElMessage({ message: '正在刷新数据...', type: 'info', duration: 1000 })
  await loadDashboardStats() // 重新加载统计数据
  await initAgeChartWithRealData()
  updateMainChartData()
  initLevelChart()
  initServiceChart()
  loadReservationData()
  loadUserProfile()
  loadNoticeList()
  ElMessage({ message: '数据已刷新', type: 'success', duration: 1000 })
}

function handleDateChange() { updateMainChartData() }

function handleViewAll() {
  router.push('/Serve/yylf/registration')
}
function handleClick(){
  router.push('/xiaoxixiaoxi/xiaoxizhongxin/messagecenter')
}
function prevDate() {
  const date = new Date(currentDate.value)
  date.setDate(date.getDate() - 1)
  currentDate.value = formatDate(date)
  loadReservationData()
}

function nextDate() {
  const date = new Date(currentDate.value)
  date.setDate(date.getDate() + 1)
  currentDate.value = formatDate(date)
  loadReservationData()
}

function today() {
  currentDate.value = formatDate(new Date())
  loadReservationData()
}

function handleShortcut1(){
  router.push('/system/task')
}
function handleShortcut2(){
  router.push('/CaiwuManage/zdgl/bill')
}
function handleShortcut3(){
  router.push('/Service/hlrw/system/arrangement/listsystem/arrangement/index/arrangement')
}
function handleShortcut4(){
  router.push('/Live/l4/zncw/bed')
}
function handleShortcut5(){
  router.push('/Serve/yylf/registration')
}
function handleShortcut6(){
  router.push('/Serve/yylf/registration')
}
function handleShortcut7(){
  router.push('/system/user')
}
function handleShortcut8(){
  router.push('/system/menu')
}

// 监听窗口大小变化，重绘图表
watch(() => window.innerWidth, () => {
  if (mainChart) mainChart.resize()
  if (levelChart) levelChart.resize()
  if (ageChart) ageChart.resize()
  if (serviceChart) serviceChart.resize()
})

// 监听当前日期变化，重新加载预约数据
watch(currentDate, () => { loadReservationData() })
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: transparent;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.grid-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.card-item {
  transition: all 0.3s ease;
}

.card-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08) !important;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h2 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.update-time {
  font-size: 12px;
  color: #999;
}

/* 数据概览样式 */
.overview-card { grid-column: span 1; }
.overview-items {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: center;
}
.overview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100px;
}
.el-progress-circle__text {
  font-size: 13px !important;
  font-weight: 500 !important;
  white-space: normal !important;
  line-height: 1.3 !important;
}

/* 我的信息样式（含系统公告） */
.info-card {
  grid-column: span 1;
  display: flex;
  flex-direction: column;
}
.user-info {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 25px;
  padding: 10px 0;
}
.main-avatar {
  border: 3px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.info-text {
  flex: 1;
  padding: 5px 0;
}
.greeting {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px 0;
  color: #333;
  line-height: 1.5;
}
.username-highlight {
  color: #409EFF;
  font-weight: 600;
}
.info-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}
.detail-row {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}
.detail-icon {
  color: #409EFF;
  width: 18px;
  height: 18px;
  flex-shrink: 0;
}
.detail-label {
  color: #666;
  width: 70px;
  flex-shrink: 0;
}
.detail-value {
  color: #333;
  flex: 1;
}

/* 系统公告样式 */
.notice-section {
  border-top: 1px dashed #eee;
  padding-top: 15px;
  margin-top: auto;
}
.notice-section h3 {
  font-size: 14px;
  margin: 0 0 12px 0;
  color: #333;
  font-weight: 600;
}
.notice-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.notice-card {
  padding: 10px;
  border-radius: 6px;
  background-color: #f9f9f9;
}
.notice-title {
  font-size: 13px;
  font-weight: 500;
  margin: 0 0 5px 0;
  color: #333;
}
.notice-content {
  font-size: 12px;
  color: #666;
  margin: 0 0 5px 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.notice-time {
  font-size: 11px;
  color: #999;
  margin: 0;
}
.empty-notice {
  text-align: center;
  padding: 20px 0;
  background-color: #f9f9f9;
  color: #999;
  font-size: 12px;
}

/* 数据统计样式 */
.stats-card {
  grid-column: span 2;
  min-height: 350px;
}
.stats-tabs { margin-bottom: 15px; }
.chart-container {
  width: 100%;
  height: 250px;
  margin-top: -80px;
}
.date-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}
.custom-date-picker { width: 240px; }

/* 快捷方式样式 */
.shortcuts-card { grid-column: span 1; }
.shortcuts-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30px;
  margin-top: 50px;
}
.shortcut-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px 5px;
  background-color: #f9f9f9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}
.shortcut-item:hover { background-color: #f0f0f0; }
.shortcut-icon {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 8px;
}
.shortcut-item p {
  margin: 0;
  font-size: 12px;
  color: #666;
}
.badge { margin-bottom: 8px; }

/* 待办事项样式 */
.todo-card {
  grid-column: span 1;
  width: 960px;
}
.todo-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 40px;
}
.todo-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.empty-chart {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.todo-tag { flex-shrink: 0; }
.todo-content { flex-grow: 1; }
.todo-title {
  margin: 0 0 3px 0;
  font-size: 14px;
  color: #333;
}
.todo-meta {
  margin: 0;
  font-size: 12px;
  color: #999;
}
.more-btn {
  font-size: 12px;
  color: #409EFF;
  padding: 0;
}
.more-btn:hover { color: #66b1ff; }

/* 预约总览样式 */
.reservation-card {
  margin-left: 230px;
  width: 500px;
  grid-column: span 1;
}
.date-nav {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  padding: 0 5px;
}
.current-date {
  font-weight: 500;
  color: #333;
}
.reservation-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.reservation-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 6px;
  border-left: 3px solid #409EFF;
}
.time-tag {
  flex-shrink: 0;
  min-width: 50px;
  text-align: center;
}
.type-tag {
  flex-shrink: 0;
  min-width: 40px;
  text-align: center;
}
.reservation-content { flex: 1; }
.reservation-content p {
  margin: 0 0 3px 0;
  font-size: 13px;
  color: #666;
}
.reservation-status { margin-top: 5px; }
.no-data {
  text-align: center;
  padding: 20px 0;
}

/* 分布图表样式 */
.distribution-card {
  grid-column: span 1;
  min-height: 280px;
}
.small-chart {
  width: 100%;
  height: 200px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .stats-card { grid-column: span 1; }
}
@media (max-width: 768px) {
  .grid-row { grid-template-columns: 1fr; }
  .overview-card, .info-card, .stats-card, 
  .shortcuts-card, .todo-card, .reservation-card,
  .distribution-card { grid-column: span 1; }
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  .date-filter {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  .custom-date-picker { width: 100%; }
  .user-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  .detail-row { justify-content: center; }
}
</style>